package org.benjamin.lending.service.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.entity.Queue;
import org.benjamin.lending.domain.entity.TransactRequest;
import org.benjamin.lending.domain.entity.TransactRequest.Status;
import org.benjamin.lending.domain.transact.TransactBean;
import org.benjamin.lending.repository.QueueRepository;
import org.benjamin.lending.repository.TransactRequestRepository;
import org.benjamin.lending.service.QueueService;
import org.benjamin.lending.service.TransactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Transactional
public class QueueServiceImpl implements QueueService {
	
	private Logger logger = LogManager.getLogger();
	
	@Autowired
	private QueueRepository queueRepository;
	
	@Autowired
	protected RestTemplate restTemplate;
	
	@Autowired
	protected TransactService transactService;
	
	@Autowired
	private TransactRequestRepository transactRequestRepository;

	@Async
	@Override
	public void execute() {
		List<Queue> queueList = this.queueRepository.findByQueueName("realNameTransactRequest");
		for(Queue queue : queueList) {
			try {
				TransactBean transactBean = new ObjectMapper().readValue(queue.getOrigMessage(), TransactBean.class);
				this.exectueRealName(transactBean);
				queue.setStatus(true);
				queue.setCompletionTime(new Timestamp(System.currentTimeMillis()));
				this.queueRepository.save(queue);
			}catch(JsonMappingException e) {
				logger.error(e.getMessage(),e);
			}catch(Exception e) {
				logger.error("执行队列中出现异常，详情:"+e.getMessage(),e);
			}
		}
	}
	
	protected void exectueRealName(TransactBean transactBean) {
		String id = transactBean.getId();
		TransactRequest transactRequest = this.transactRequestRepository.findOne(id);
		if(transactRequest.getStatus().equals(Status.READY)) {
			transactRequest.setStatus(Status.SEND);
			HttpHeaders httpHeaders = new HttpHeaders();
			Set<String> keyArray = transactBean.getParamterMap().keySet();
			for(String key : keyArray) {
				httpHeaders.add(key, transactBean.getParamterMap().get(key).toString());
			}
			httpHeaders.set(HttpHeaders.ACCEPT_ENCODING, "UTF-8");
			Map<String,Object> resultMap = this.restTemplate.postForObject(transactBean.getTargetUrl(), httpHeaders, HashMap.class);
			this.transactRequestRepository.save(transactRequest);
			this.transactService.realNameResponse(resultMap);
		}
	}

}
